<template>
  <li>
    <div :class="{ bold: isFolder }" @click="toggle" @dblclick="makeFolder">
      {{ item?.name }}<span v-if="isFolder">[{{ isOpen ? "-" : "+" }}]</span>
    </div>
    <ul v-show="isOpen" v-if="isFolder">
      <recursion-item
        class="item"
        v-for="child in item?.children"
        :item="child"
        @make-folder="$emit('make-folder', $event)"
        @add-item="$emit('add-item', $event)"
      ></recursion-item>
      <li class="add" @click="$emit('add-item', item)">+</li>
    </ul>
  </li>
</template>

<script lang="ts">
import { defineComponent, PropType, inject } from "vue";
import { IRecursionItem } from '@/interface';

export default defineComponent({
  name: "recursionItem",
  props: {
    item: Object as PropType<IRecursionItem>,
  },
  setup() {
    const color = inject('$color');
    return { color };
  },
  data: function () {
    return {
      isOpen: false,
    };
  },
  computed: {
    isFolder(): boolean {
      // @ts-ignore
      return this.item.children && this.item.children.length;
    },
  },
  methods: {
    toggle() {
      if (this.isFolder) {
        this.isOpen = !this.isOpen;
      }
    },
    makeFolder() {
      if (!this.isFolder) {
        this.$emit("make-folder", this.item);
        this.isOpen = true;
      }
    },
  },
});
</script>

<style>
.wrapper {
  font-family: Menlo, Consolas, monospace;
  color: v-bind(color);
}
.item {
  cursor: pointer;
}
.bold {
  font-weight: bold;
}
ul {
  padding-left: 1em;
  line-height: 1.5em;
  list-style-type: dot;
}
</style>